/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.ingsoc2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 * @author sfreiman
 */
public class PersonaDAOHSQL implements PersonaDAO {
        Connection conn;

    public PersonaDAOHSQL (Connection myconn){
        conn=myconn;
    }
    public boolean crear (Persona pp) throws SQLException{
        String query;

        query = "INSERT INTO Personas (dni , nombre ,apellido) VALUES(?,?,?)";

        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, pp.getDni());
        pstmt.setString(2, pp.getNombre()); 
        pstmt.setString(3, pp.getApellido()); 
        return pstmt.executeUpdate()>0;
        
    }
    
    public boolean borrar (Persona pp)throws SQLException{
        
        String query;
        PreparedStatement pstst;
        query = "DELETE from Personas WHERE dni =?";
        
        pstst=conn.prepareStatement(query);
        pstst.setInt(1, pp.getDni());
        return pstst.executeUpdate()==1;
    }
    
    public boolean guardar (Persona pp)throws SQLException{
        String query;     
        query = "UPDATE Personas SET nombre=?  , apellido=? WHERE DNI=?";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, pp.getNombre()); 
        pstmt.setString(2, pp.getApellido()); 
        pstmt.setInt(3, pp.getDni());
        return pstmt.executeUpdate()==1;
    }
    
    public List<Persona> listar () throws SQLException{
        String query;
        Statement stst;
        ResultSet  rst1;  
        List listaDePersonas=new ArrayList<Persona>();
        
        Persona nPersona;
        
        query ="SELECT * FROM Personas";
        stst=conn.createStatement();
        rst1=stst.executeQuery(query);
        while (rst1.next()){  
            nPersona=new Persona();
            nPersona.setNombre(rst1.getString("nombre"));
            nPersona.setApellido(rst1.getString("apellido"));
            nPersona.setDni(rst1.getInt("dni"));
            listaDePersonas.add(nPersona);
        }  
         
        return listaDePersonas;
    }
    
}